package org.example.managere.service.feibiao.impl;

import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmKnowledgeFailureDto;
import org.example.managere.dto.feibiao.AmKnowledgeBasicDto;
import org.example.managere.entity.feibiao.AmKnowledgeBasic;
import org.example.managere.entity.feibiao.AmKnowledgeFailure;
import org.example.managere.repository.feibiao.AmKnowledgeBasicRepository;
import org.example.managere.repository.feibiao.AmKnowledgeFailureRepository;
import org.example.managere.service.feibiao.AmKnowledgeFailureService;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.hibernate.Hibernate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 电机故障信息服务实现类 - 电机向量知识库 (精简版)
 */
@Service
@RequiredArgsConstructor
public class AmKnowledgeFailureServiceImpl implements AmKnowledgeFailureService {
    
    private final AmKnowledgeFailureRepository failureRepository;
    private final AmKnowledgeBasicRepository basicRepository;
    private final ModelMapper modelMapper;
    
    @PersistenceContext
    private EntityManager entityManager;
    
    /**
     * 将实体转换为DTO
     */
    private AmKnowledgeFailureDto convertToDto(AmKnowledgeFailure entity) {
        AmKnowledgeFailureDto dto = modelMapper.map(entity, AmKnowledgeFailureDto.class);
        
        // 设置关联电机信息的展示字段
        if (entity.getMotorId() != null) {
            AmKnowledgeBasic basic = entity.getMotorId();
            dto.setMotorId(basic.getMotorId());
            dto.setMotorType(basic.getMotorType());
            dto.setManufacturer(basic.getManufacturer());
        }
        
        return dto;
    }
    
    /**
     * 将DTO转换为实体
     */
    private AmKnowledgeFailure convertToEntity(AmKnowledgeFailureDto dto) {
        AmKnowledgeFailure entity = modelMapper.map(dto, AmKnowledgeFailure.class);
        
        // 设置关联电机
        if (dto.getMotorId() != null) {
            Optional<AmKnowledgeBasic> basicOptional = basicRepository.findById(dto.getMotorId());
            if (basicOptional.isPresent()) {
                entity.setMotorId(basicOptional.get());
            }
        }
        
        return entity;
    }
    
    @Override
    @Transactional
    public AmKnowledgeFailureDto save(AmKnowledgeFailureDto dto) {
        AmKnowledgeFailure entity = convertToEntity(dto);
        AmKnowledgeFailure savedEntity = failureRepository.save(entity);
        return convertToDto(savedEntity);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<AmKnowledgeFailureDto> findById(Integer id) {
        // 使用连接查询
        return failureRepository.findByIdWithMotor(id)
                .map(this::convertToDto);
    }
    
    @Override
    @Transactional
    public AmKnowledgeFailureDto update(AmKnowledgeFailureDto dto) {
        // 确保记录存在
        if (dto.getId() == null || !failureRepository.existsById(dto.getId())) {
            throw new IllegalArgumentException("无法更新不存在的记录，ID: " + dto.getId());
        }
        
        AmKnowledgeFailure entity = convertToEntity(dto);
        AmKnowledgeFailure savedEntity = failureRepository.save(entity);
        return convertToDto(savedEntity);
    }
    
    @Override
    @Transactional
    public void deleteById(Integer id) {
        failureRepository.deleteById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AmKnowledgeFailureDto> findAll() {
        // 使用连接查询获取所有故障记录及其关联的电机信息
        return failureRepository.findAllWithMotors().stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<AmKnowledgeFailureDto> findAll(Pageable pageable) {
        // 首先获取当前页的ID列表
        Page<AmKnowledgeFailure> failurePage = failureRepository.findAll(pageable);
        List<Integer> ids = failurePage.getContent().stream()
                .map(AmKnowledgeFailure::getId)
                .collect(Collectors.toList());
        
        if (ids.isEmpty()) {
            return Page.empty(pageable);
        }
        
        // 使用ID列表查询完整数据
        Page<AmKnowledgeFailure> detailedPage = failureRepository.findByIdInWithPagination(ids, pageable);
        return detailedPage.map(this::convertToDto);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<AmKnowledgeFailureDto> searchByKeyword(String keyword, Pageable pageable) {
        return failureRepository.searchByKeyword(keyword, pageable)
                .map(this::convertToDto);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AmKnowledgeFailureDto> findByMotorId(String motorId) {
        return failureRepository.findByMotorId_MotorId(motorId).stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AmKnowledgeFailureDto> findUnrepairedFailures() {
        return failureRepository.findByRepairTimeIsNull().stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public long countUnrepairedFailures() {
        return failureRepository.countByRepairTimeIsNull();
    }
    
    @Override
    @Transactional(readOnly = true)
    public Double findAverageRepairEfficiency() {
        return failureRepository.findAverageRepairEfficiency();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<AmKnowledgeBasicDto> findAllMotors() {
        // 返回所有电机基础信息
        return basicRepository.findAll().stream()
                .map(basic -> modelMapper.map(basic, AmKnowledgeBasicDto.class))
                .collect(Collectors.toList());
    }
} 